package com.zzsource.yuapicliensdk.model.response;

import cn.hutool.core.bean.BeanUtil;
import com.zzsource.yuapicliensdk.annotation.MyApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.lang.reflect.Field;
import java.util.*;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class DataInfo<T> {
    private T value;
    private Integer type;
    private String key;
    private String key_zh;

    private static Map<Field, MyApiModelProperty> MAP = new HashMap<>();

    public static List<DataInfo> buildResponse(Object object, Class classz) {
        Map<String, Object> map = BeanUtil.beanToMap(object);
        List<DataInfo> list = new ArrayList<>();
        Field[] fields = classz.getDeclaredFields();
        for (Field field : fields) {
            // 从缓存中查询
            MyApiModelProperty annotation = MAP.get(field);
            if(Objects.isNull(annotation)){
                if(Objects.isNull(annotation = field.getAnnotation(MyApiModelProperty.class))){
                    continue;
                } else {
                    MAP.put(field, annotation);
                }
            }
            String key = annotation.key();
            DataInfo<Object> dataInfo = DataInfo.builder()
                    .key(key)
                    .key_zh(annotation.key_zh())
                    .value(map.get(key))
                    .type(annotation.type().getType())
                    .build();
            list.add(dataInfo);
        }
        return list;
    }

    public static void main(String[] args) {
        PoisonousChickenSoupResponse response = new PoisonousChickenSoupResponse();
        response.setText("21312321");
        System.out.println(buildResponse(response, PoisonousChickenSoupResponse.class));
        BiResponse biResponse = new BiResponse();
        System.out.println(buildResponse(biResponse, BiResponse.class));
        System.out.println(buildResponse(response, PoisonousChickenSoupResponse.class));
    }
}
